<?php
	class message_model extends Model
	{      
    	//pre set read options in db
		public function __construct(){
			parent::__construct();
			$this->setTableName('messages');
            //need using options model, and set, put options in db
 		}
		
        /*
        	@param string content of message to send
            @param int? userid of message sending user, null present as system
            @param array? userid of message receiving user, null present as broadcasting
			@param int? related task id
            @return bool message sending successful or not
        */
		public function send($msg, $fromId = null, $toId = null, $taskId = null){
			//data assertion
            $originMsg = $msg;
            $msg = $this->_encryptMessage($msg);
            $userModel = $this->load->model('user');
            $taskModel = $this->load->model('task');
            
            if (empty($fromId))
            	$fromId = null;
            else{
            	$fromId = intval($fromId);
                if (!$userModel->exists($fromId)){
                	return false;
                }
            }
            
            if (empty($toId))
            	$toId = null;
            else{
            	$toId = intval($toId);
                if (!$userModel->exists($toId)){
                	return false;
                }
            }
            
            if (empty($taskId))
            	$taskId = null;
            else{
            	$taskId = intval($taskId);
                if (!taskModel->exists($taskId)){
                	return false;
                }
            }
            
            $thisTableName = $this->getTableName();
            $userTableName = $userModel->getTableName();
            $taskTableName = $taskModel->getTableName();
            
            $sql = 'insert into ' . $thisTableName;
            $sql .= ' (from_user_id, to_user_id, content, send_date, relate_task_id) ';
            $sql .= ' values({0}, {1}, {2}, now(), {3}) ';
            
            if (!$this->db->query($sql, array($fromId, $toId, $msg, $taskId))){
            	return false;
            }
            
            //now generate sending user id list
            if (null == $toId){
            	if (null == $taskId){
                	//with no task and no to user id
                    //send to all user
                    $userList = $userModel->getUserList();
                }
                else{
                	$userList = $this->load->model('privilege')->getViewUserList($taskId);
                }
            }
            else{
            	$userList = array($userModel->getUserInfo());
            }
            
            return $this->_doSendMessage($originMsg, $userList);
        }
        
        /*
        	@param array options specified
            @return array? message list
        */
        public function fetch($options, $sqlSuffix){
        	$userModel = $this->load->model('user');
            $taskModel = $this->load->model('task');
            
			//assertions
            unset($options['id']);
            
            if (isset($options['from_user_id'])){
            	if (empty($options['from_user_id']))
                	$options['from_user_id'] = null;
                else{
                	$options['from_user_id'] = intval($options['from_user_id']);
                	if (!$userModel->exists($options['from_user_id'])){
                    	return false;	
                    }
                }
            }
            
            if (isset($options['to_user_id'])){
            	if (empty($options['to_user_id']))
                	$options['to_user_id'] = null;
                else{
                	$options['to_user_id'] = intval($options['to_user_id']);
                    if (!$userModel->exists($options['to_user_id'])){
                    	return false;
                    }
                }
            }
            
           	if (isset($options['relate_task_id'])){
            	if (empty($options['relate_task_id'])
                	$options['relate_task_id'] = null;
                else{
                	$options['relate_task_id'] = intval($options['relate_task_id']);
                    if (!$taskModel->exists($options['relate_task_id']){
                    	return false;
                    }
                }
            }
            
            $thisTableName = $this->getTableName();
            $userTableName = $userModel->getTableName();
            $taskTableName = $taskModel->getTableName();
            
            $sql = 'select tblM.id as id, from_user_id, to_user_id, ';
            $sql .= 'content, send_date, relate_task_id, ';
            $sql .= 'tblA.username as from_user_name, ';
            $sql .= 'tblB.username as to_user_name , ';
            $sql .= 'tblT.name as relate_task_name ';
            $sql .= (' from ' . $thisTableName . ' as tblM ');
            $sql .= (', ' . $userTableName . ' as tblA ');
			$sql .= (', ' . $userTableName . ' as tblB ');
            $sql .= (', ' . $taskTableName . ' as tblT ');
            $sql .= ' where ';
            $sql .= ' tblA.id = tblM.from_user_id ';
            $sql .= ' and tblB.id = tblM.to_user_id ';
            $sql .= ' and tblT.id = tblM.relate_task_id ';
            //where segment by user definitions
            foreach(array_keys($options) as $i => $key){
            	$sql .= (' and tblM.' . $key . ' = {' . $i . '} ');
            }
            $sql .= $sqlSuffix;
            
            $info = $this->db->fetch($sql, array_values($options));
            
            if (!empty($info)){
            	foreach($info as &$val){
                	$val['content'] = $this->_decryptMessage($val['content']);
                }
           	}
            
            return $info;
        }
        
        /*
        	@param int id of message to fetch info of
            @return array info of specified message
        */
        public function fetchInfo($id){
        	//fetch id specified message info
            $id = intval($id);
            
            if (empty($id)) return false;
            
            $sql = 'select * from ' . $this->getTableName()
            	. ' where id = {0} limit 1';
            return $this->db->fetchOne($sql, array($id));
        }
        
        /*
        	@param int id of message to check existence
            @return bool state of message existence
        */
        public function exists($id){
        	//assert id as int
			$result = $this->fetchInfo($id);
            
            return !empty($result);
        }
        
		/*
        	@param string message
            @return string encrypted message
        */
        private function _encryptMessage($msg){
        	//easy encrypt using base64
            
            //strip tags
            $msg = strip_tags($msg, '<a><br>');
            
            //make \n or \r\n as a <br />
            str_replace(array("\r\n", "\n"), '<br />', $msg);
            
            return base64_encode($msg);
        }
        
        
        /*
        	@param string encrypted message
            @return string message decrypted
        */
        private function _decryptMessage($msg){
        	return base64_decode($msg);
        }
        
        /*
        
        */
        private function _doSendMessage($msg, $list){
            return true;
        }
        
        
        /*
        
        */
        private function _doSendMail(){
        
        
        }
        
        /*
        
        */
        private function _doSendSMS(){
        
        }
	}

